import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import moment from 'moment';
import qs from 'qs';
import _ from 'lodash';

import { addTab, timeLimit } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Badge,
  DatePicker,
  Button,
  Table,
  Tooltip,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { pathname } = window.location;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { Item } = Form;

interface WithdrawalRecordsProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  withdrawalList: any;
  screen: string;
}

interface WithdrawalRecordsState {
  searchValues: any;
  pageNum: number;
  numPerPage: number;
  rowId:number;
}

function mapStateToProps(state: any) {
  const {
    withdrawalRecords: { withdrawalList },
    global: { screen },
    loading,
  } = state;

  return {
    withdrawalList,
    screen,
    loading: loading.effects['withdrawalRecords/fetch'],
  };
}

@connect(mapStateToProps)

class WithdrawalRecordsElem extends Component<WithdrawalRecordsProps, WithdrawalRecordsState> {
  columns = [
    {
      title: '流水号',
      dataIndex: 'serial_num',
      width: 230,
    },
    {
      title: '合作商',
      dataIndex: 'name',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '提现金额(元)',
      dataIndex: 'amount',
      width: 120,
      render: (text: number) => (text / 100).toFixed(2),
    },
    {
      title: '手续费(元)',
      width: 120,
      dataIndex: 'withdraw_service_fee',
      render: (text: number) => (text / 100).toFixed(2),
    },
    {
      title: '提现方式',
      dataIndex: 'pay_way_desc',
    },
    {
      title: '提现账号',
      dataIndex: 'pay_account',
      width: 150,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '上级合作商',
      dataIndex: 'parent_name',
      width: 150,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text: number) => (
        text === 13103
          ? <Badge status="success" text="支付完成" />
          : <Badge status="error" text="支付失败" />
      ),
    },
    {
      title: '提现时间',
      dataIndex: 'settle_time',
      width: 180,
    },
    {
      title: '操作人',
      width: 150,
      dataIndex: 'oper_name',
    },
  ]

  state: WithdrawalRecordsState = {
    searchValues: {},
    pageNum: 1,
    numPerPage: 20,
    rowId: 0,
  }

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...searchValues } = query;

    return {
      ...state,
      searchValues,
      pageNum: Number(page) || 1,
      numPerPage: Number(psize) || (props.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { withdrawalList } = this.props;
    if (withdrawalList?.list?.length) return;

    this.fetchRechargeList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageNum, numPerPage } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageNum !== prevState.pageNum
      || numPerPage !== prevState.numPerPage) {
      this.setFieldsValue();
      this.fetchRechargeList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const {
      searchValues: { start_time, end_time, ...others },
    } = this.state;

    const momentDate = [
      start_time ? moment(start_time) : moment(moment().subtract(15, 'days').format('YYYY-MM-DD')),
      end_time && moment(end_time),
    ];
    others.momentDate = momentDate;

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(others);
  }

  // 获取数据
  fetchRechargeList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'withdrawalRecords/fetch',
      payload: this.getQueryParams(),
    });
  }

  // 获取查询参数
  getQueryParams = () => {
    const { searchValues, pageNum, numPerPage } = this.state;
    return {
      ...searchValues,
      pageNum,
      numPerPage,
    };
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (!errors) {
        const { momentDate = [], ...query } = values;
        const params = {
          ...query,
          start_time: momentDate[0] ? moment(momentDate[0]).format('YYYY-MM-DD') : '',
          end_time: momentDate[1] ? moment(momentDate[1]).format('YYYY-MM-DD') : '',
          page: 1,
          psize: 20,
        };

        const { dispatch } = this.props;
        addTab(dispatch, {
          name: '提现记录',
          url: `${pathname}?${qs.stringify(params)}`,
          isTopMenu: true,
        });
      }
    });
  }

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '提现记录',
      url: pathname,
      isTopMenu: true,
    });
  }

  handlePerPage = (page: number, psize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, page, psize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '提现记录',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction(typeName: string, payload: any) {
    const { dispatch } = this.props;
    dispatch({
      type: `withdrawalRecords/${typeName}`,
      payload,
    });
  }

  render() {
    const { pageNum, numPerPage } = this.state;
    const { form: { getFieldDecorator }, loading, withdrawalList } = this.props;
    const pagination: object = withdrawalList
      ? {
        total: withdrawalList ? withdrawalList.count : 0,
        pageSize: numPerPage,
        current: pageNum,
        onChange: this.handlePerPage,
        showTotal: () => `共${withdrawalList.count || 0}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onShowSizeChange: this.handlePerPage,
        showQuickJumper: true,
      }
      : {};

    const dataSource = withdrawalList.list || [];

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form hideRequiredMark onSubmit={this.handleSearch} className="tableListForm">
            <Row gutter={12}>
              <Col md={12} sm={24}>
                <Item label="　起止时间" colon={false}>
                  {getFieldDecorator('momentDate')(
                    <RangePicker
                      placeholder={['开始时间', '截止时间']}
                      style={{ width: '100%' }}
                      format="YYYY/MM/DD"
                      disabledDate={timeLimit}
                      ranges={{
                        今天: [moment().startOf('day'), moment().endOf('day')],
                        本周: [moment().startOf('week'), moment().endOf('week')],
                        本月: [moment().startOf('month'), moment().endOf('month')],
                        上月: [
                          moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                          moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                        ],
                      }}
                    />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　　　状态" colon={false}>
                  {getFieldDecorator('status')(
                    <Select placeholder="请选择" allowClear>
                      <Option value="13103">支付完成</Option>
                      <Option value="13104">支付失败</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="交易流水号" colon={false}>
                  {getFieldDecorator('serial_num')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　合作商家" colon={false}>
                  {getFieldDecorator('fcs_name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　手机号码" colon={false}>
                  {getFieldDecorator('phone')(
                    <Input
                      allowClear
                      type="number"
                      placeholder="请输入"
                    />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>
        <Card bordered={false} className="tableList">
          <Table
            rowKey="id"
            tableLayout="fixed"
            loading={loading}
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            scroll={{ x: 1500 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create()(WithdrawalRecordsElem);
